// 初始化摄像头
async function initCamera() {
    try {
        const video = document.getElementById('video');
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        video.srcObject = stream;
    } catch (err) {
        console.error('摄像头访问失败:', err);
    }
}

// 截图处理
function captureImage() {
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const context = canvas.getContext('2d');
    
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    return new Promise((resolve) => {
        canvas.toBlob((blob) => {
            resolve(blob);
        }, 'image/jpeg');
    });
}

// 上传图片处理
function handleUpload(file) {
    const formData = new FormData();
    formData.append('image', file);
    return sendToServer(formData);
}

// 发送到服务器分析
async function sendToServer(formData) {
    try {
        showLoading(true);
        const response = await fetch('/analyze', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        if (data.error) throw new Error(data.error);
        
        updateResults(data.class, data.advice);
    } catch (err) {
        showError(err.message);
    } finally {
        showLoading(false);
    }
}

// 显示加载状态
function showLoading(show) {
    document.querySelector('.loading').style.display = show ? 'block' : 'none';
}

// 更新结果展示
function updateResults(className, advice) {
    document.getElementById('classResult').innerHTML = `<h3>诊断结果：${className}</h3>`;
    document.getElementById('adviceResult').innerHTML = `<p>${advice.replace(/\n/g, '<br>')}</p>`;
}

// 错误处理
function showError(msg) {
    alert('发生错误：' + msg);
}

// 事件绑定
document.addEventListener('DOMContentLoaded', () => {
    initCamera();
    
    // 拍摄按钮
    document.getElementById('capture').addEventListener('click', async () => {
        const blob = await captureImage();
        const file = new File([blob], 'capture.jpg', { type: 'image/jpeg' });
        handleUpload(file);
    });
    
    // 文件上传
    document.getElementById('upload').addEventListener('change', (e) => {
        if (e.target.files[0]) {
            handleUpload(e.target.files[0]);
        }
    });
});